<template>
  <div id="forest">
    <div id="forestContainer"></div>
    <el-card id="extend" v-show="!isHidden" @click="hidden">+</el-card>
    <el-card id="dataTable" v-show="isHidden">
      <div id="hiddenButton" @click="hidden">-</div>
      <!-- 输入搜索的城市 -->
      <el-select
        v-model="searchProvince"
        placeholder="Select"
        size="large"
        @change="getForestData"
      >
        <el-option
          v-for="item in cityOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!--切换视图  -->
      <el-tabs v-model="activeName" @tab-click="tabChange">
        <!-- 表格 -->
        <el-tab-pane label="表格" name="table">
          <el-table
            id="forestDataTable"
            :data="forestTableData.data"
            fit
            show-header
            :default-sort="{ prop: 'year', order: 'descending' }"
          >
            <el-table-column
              prop="year"
              label="年份"
              sortable
            ></el-table-column>
            <el-table-column
              prop="area"
              label="覆盖面积(万公顷)"
            ></el-table-column>
            <el-table-column prop="coverage" label="覆盖率"></el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 柱状图 -->
        <el-tab-pane label="柱形图" name="columnar">
          <div id="forestDataColContainer" ref="forestDataColContainer"></div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, onActivated, onDeactivated } from "vue";
import { shallowRef } from "@vue/reactivity";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessage } from "element-plus";

import axios from "axios";
import { cityOption } from "@/tools/cityOptions.js";
import { forestDataReq } from "@/networks/energy/forest.js";
import * as echarts from "echarts";
export default {
  name: "forest",
  setup() {
    window._AMapSecurityConfig = {
      //注册安全密钥
      securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
    };
    const map = shallowRef(); //地图容器
    const searchProvince = ref(null); //搜索的城市
    const activeName = ref("table"); //数据的展示方式
    let autoColor = "#67C23A";
    const cityOptions = cityOption;
    let forestTableData = reactive({ data: [] });
    let isHidden = ref(true);
    // 创建地图
    const initMap = function () {
      if (map.value) {
        map.value.destroy();
        map.value.clearMap();
        // console.log("已清理图层");
      }
      AMapLoader.load({
        key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      })
        .then((AMap) => {
          map.value = new AMap.Map("forestContainer", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [117.301291, 31.844148], //初始化地图中心点位置
            mapStyle: "amap://styles/darkblue",
          });
          //导入地图插件
          AMap.plugin(
            ["AMap.ToolBar", "AMap.Geolocation", "AMap.DistrictSearch"],
            async function () {
              map.value.addControl(new AMap.Geolocation());
            }
          );
          //   绘制行政区
          let district = new AMap.DistrictSearch({
            // 返回行政区边界坐标等具体信息
            extensions: "all",
            // 设置查询行政区级别为 区
            level: "province",
          });
          if (searchProvince.value != null) {
            district.search(searchProvince.value, function (status, result) {
              // 获取朝阳区的边界信息
              let bounds = result.districtList[0].boundaries;
              let polygons = [];
              if (bounds) {
                for (let i = 0, l = bounds.length; i < l; i++) {
                  //生成行政区划polygon
                  let polygon = new AMap.Polygon({
                    map: map.value,
                    strokeWeight: 1,
                    path: bounds[i],
                    fillOpacity: forestTableData.data[0].coverage / 100,
                    fillColor: autoColor,
                    strokeColor: "#CC66CC",
                  });
                  polygons.push(polygon);
                }
                // 地图自适应
                map.value.setFitView();
              }
            });
          }
        })
        .catch((e) => {
          console.log(e);
        });
    };

    // 显示森林覆盖数据
    const getForestData = async function () {
      await getData(searchProvince.value); //获取数据
      initMap(); //重载地图
    };

    //从后台获取数据
    const getData = async function (cityName) {
      if (!cityName) {
        return;
      } else {
        try {
          const { data: res } = await forestDataReq({ cityName: cityName }); //获取数据，发送请求
          // console.log(res);
          // forestTableData.data.length = 0;
          // for(let i =0;i<res.length;i++)
          // {
          //   forestTableData.data.push(res[i]);
          // }
          forestTableData.data = reactive(res); //setUp先于一切生命周期函数，因此在template层直接挂载对象后，若在js中覆盖原对象，由于template对于原对象的引用依然存在就会造成页面无法更改的问题
          // console.log(forestTableData);
        } catch (err) {
          console.log(err);
        }
      }
    };

    function hidden() {
      isHidden.value = !isHidden.value;
    }

    // 生命周期
    onActivated(() => {
      initMap();
    });

    onDeactivated(() => {
      if (map.value) {
        map.value.destroy();
      }
    });

    // 监听年份改变

    return {
      searchProvince,
      cityOptions,
      activeName,
      getForestData,
      forestTableData,
      isHidden,
      hidden,
    };
  },

  data() {
    return {};
  },
  methods: {
    //创建柱状图
    createColumnarChart() {
      if (
        this.$refs.forestDataColContainer == null ||
        this.forestTableData.data.length == 0
      ) {
        return;
      }

      echarts.dispose(this.$refs.forestDataColContainer);
      let forestChart = echarts.init(this.$refs.forestDataColContainer);
      let area = [];
      let coverage = [];
      for (let i = 0; i < this.forestTableData.data.length; i++) {
        area.unshift(this.forestTableData.data[i].area);
        coverage.unshift(this.forestTableData.data[i].coverage);
      }
      // 柱状图配置项
      forestChart.setOption({
        title: {
          text: "2012-2020年森林覆盖面积/覆盖率",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          left: "right",
          top: "25",
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: { readOnly: false },
            magicType: { type: ["line", "bar"] },
            restore: {},
            saveAsImage: {},
          },
        },
        xAxis: {
          name: "年份",
          data: [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020],
          type: "category",
          boundaryGap: false,
        },
        yAxis: {
          name: "覆盖面积/覆盖率",
          type: "value",
          offset: "20",
        },
        series: [
          {
            name: "覆盖面积",
            type: "bar",
            data: area,
          },
          {
            name: "覆盖率",
            type: "bar",
            data: coverage,
          },
        ],
      });
      console.log("图表创建完成");
    },

    // 改变数据显示方式时触发
    tabChange() {
      if (this.activeName == "columnar") {
        this.$nextTick(() => {
          this.createColumnarChart();
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
#forestContainer {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
  z-index: 1;
}

#dataTable {
  // height: 100px;
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  #forestDataTable {
    height: auto;
    width: 30vw;
    #el-table-column {
      width: 180px;
      color: rgb(50, 250, 0);
    }
  }

  #forestDataColContainer {
    width: 30vw;
    height: 50vh;
    margin: 20px 50px;
  }
}

#hiddenButton {
  position: absolute;
  right: 20px;
  font-size: 3rem;
  top: -10px;
  cursor: pointer;
}

#extend {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  font-size: 2rem;
  cursor: pointer;
}
</style>
